package com.hcbd.tdwt.ui.xingyu.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.cy.translucentparent.StatusNavUtils;

import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO_Table;
import com.hcbd.tdwt.util.AppUtil;
import com.hcbd.tdwt.util.CharacterParser;
import com.hcbd.tdwt.util.PinyinComparator;
import com.hcbd.tdwt.view.SideBar;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.adapter.AddressBookAdapter;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact_Table;
import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activitiy_address_book)
public class AddressBookActivity extends BaseActivity implements AddressBookAdapter.OnItemClickListener {
    private String TAG = "AddressBookActivity";
   @ViewById(R.id.contact_search_edit)
    EditText contactSearchEdit;
    @ViewById(R.id.contact_recyclerview)
    RecyclerView contactRecyclerview;
    @ViewById(R.id.contact_index_tv)
    TextView contactIndexTv;
    @ViewById(R.id.contact_index_sideBar)
    SideBar contactIndexSideBar;
    @ViewById
    ImageView addContactImg;
    /*******************************************(只是单纯的强迫症想分割一下)******************************************************/
    //联系人列表适配器
    private AddressBookAdapter addressBookAdapter;
    //记录当前位置
    private int mIndex;
    //是否需要滚动第二次
    private boolean move = false;
    //联系人数据
    private List<BoxContact> userList;
    // 汉字转换成拼音的类
    private CharacterParser characterParser;
    // 根据拼音来排列ListView里面的数据类

    private PinyinComparator pinyinComparator;

    private int entryMode;//1主页进入,2消息界面进入
    @AfterViews
    protected void init(){
        entryMode=getIntent().getIntExtra("entryMode",0);
        // 实例化拼音比较器
        pinyinComparator = new PinyinComparator();
        initList();
        contactSearchEdit.requestFocus();
        showInputKeybord(contactSearchEdit);
        StatusNavUtils.setStatusNavBarColor(this, getColor(R.color.white), getColor(R.color.deep_black));
        setAndroidNativeLightStatusBar(true);
    }
    private final int ADD_CONTACT_CODE=5;//添加联系人返回
    @Click
    void addContactImg(){
        Intent intent=new Intent();
        if(BdToolFactory.app_type==BdToolFactory.HLCT_BG_TYPE){
            intent.setClass(this, com.hcbd.tdwt.ui.fuda.common.activity.AddContactActivity_.class);
        }else{
            intent.setClass(this, AddContactActivity_.class);
        }
        startActivityForResult(intent,ADD_CONTACT_CODE);
    }
    @Click
    void headLeft(){
        finish();
    }
    @OnActivityResult(ADD_CONTACT_CODE)
    public void resultContact(int resultCode){
        if(resultCode== Activity.RESULT_OK){
            updateList();
            EventBus.getDefault().post("onMessage");
        }
    }

    private void initList() {
        userList = new ArrayList<>();
        addressBookAdapter = new AddressBookAdapter(this, userList, this);
        contactRecyclerview.setAdapter(addressBookAdapter);
        contactRecyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(this, R.drawable.recyclerview_divider)));
        contactRecyclerview.addItemDecoration(divider);
        //滚动监听
        contactRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //在这里进行第二次滚动（最后的距离）
                if (move) {
                    move = false;
                    //获取列表视图
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                    int n = mIndex - layoutManager.findFirstVisibleItemPosition();
                    if (0 <= n && n < recyclerView.getChildCount()) {
                        //获取要置顶的项顶部离RecyclerView顶部的距离
                        int top = recyclerView.getChildAt(n).getTop();
                        //最后的移动
                        recyclerView.scrollBy(0, top);
                    }
                }
            }
        });

        //侧边索引栏
        contactIndexSideBar.setTextView(contactIndexTv);
        // 设置右侧触摸监听
        contactIndexSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = addressBookAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    moveToPosition(position);
                }
            }
        });
        updateList();
    }
    @AfterTextChange(R.id.contact_search_edit)
    void contactSearch(){
        String searchContent=getTextStr(contactSearchEdit);
        if (!TextUtils.isEmpty(searchContent)) {
            if (addressBookAdapter != null) {
                addressBookAdapter.setSearchingString(searchContent);
                searchList(searchContent);
            }
        } else {// 如果输入框内容为空，显示全部
            if (addressBookAdapter != null) {
                addressBookAdapter.setSearchingString("");
                searchList("");
            }
        }
    }

    /**
     * 移动到指定位置
     *
     * @param index
     */
    private void moveToPosition(int index) {
        //获取列表视图
        LinearLayoutManager layoutManager = (LinearLayoutManager) contactRecyclerview.getLayoutManager();
        //获取当前recycleView屏幕可见的第一项和最后一项的Position
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (index <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            contactRecyclerview.scrollToPosition(index);
        } else if (index <= lastItem) {
            //当要置顶的项已经在屏幕上显示时，计算它离屏幕原点的距离
            int top = contactRecyclerview.getChildAt(index - firstItem).getTop();
            contactRecyclerview.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            contactRecyclerview.scrollToPosition(index);
            //记录当前需要在RecyclerView滚动监听里面继续第二次滚动
            move = true;
            mIndex = index;
        }
    }


    /**
     * 更新列表
     */
    private void updateList() {
        List<BoxContact>list= SQLite.select().from(BoxContact.class).where(BoxContact_Table.boxId.notEq(GlobalParams.commandCentreNumber)).queryList();
        //更新列表
        userList.clear();

        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        //设置用户首字母
        for (int i = 0; i < list.size(); i++) {
            BoxContact boxContact = list.get(i);
            if(boxContact.getBoxId()==null){
                continue;
            }
            if (boxContact.getBoxId().equals(GlobalParams.commandCentreNumber)) {
                continue;
            }
            boxContact.setSortName();
            userList.add(boxContact);
        }
        // 按拼音首字母排序
        if (list.size() > 1) {
            userList.sort(pinyinComparator);
        }
        addressBookAdapter.upDateList(userList, false);
    }

    /**
     * 更新列表
     *
     * @param
     */
    private void updateSearchList(List<BoxContact> list, boolean isSearch) {
        if (isSearch) {

            // 实例化汉字转拼音类
            characterParser = CharacterParser.getInstance();
            //设置用户首字母
            for (int i = 0; i < list.size(); i++) {
                BoxContact boxContact = list.get(i);
                boxContact.setSortName();
            }
            // 按拼音首字母排序
            if (list.size() > 1) {
                list.sort(pinyinComparator);
            }
        }
        addressBookAdapter.upDateList(list, isSearch);
    }


    private static int lastest = 0;

    /**
     * 搜索列表
     */
    private void searchList(final String s) {
        final int i = ++lastest;
        // 开一个线程来进行快速搜索
        new Thread(() -> {
            List<BoxContact> boxContacts;
            final boolean isSearch;
            if (TextUtils.isEmpty(s)) {
                boxContacts = userList;
                isSearch = false;
            } else {
                boxContacts =search(s, userList);
                isSearch = true;
            }
            if (i == lastest) {
                // 避免线程同步问题
                final List<BoxContact> finalBoxContacts = boxContacts;
                runOnUiThread(() -> {
                    if (i == lastest) {
                        // 避免线程同步问题
                        if (finalBoxContacts != null) {
                            updateSearchList(finalBoxContacts, isSearch);
                        }
                    }
                });
            }
        }).start();
    }
    public  List<BoxContact> search(final String str, final List<BoxContact> boxContactList) {
        List<BoxContact> searchData = new ArrayList<>();
        if (!TextUtils.isEmpty(str)) {
            for (BoxContact b : boxContactList) {
                if (b.getBoxId()!=null&&b.getBoxId().contains(str)) {
                    searchData.add(b);
                } else if (b.getName() != null && b.getName().contains(str)) {
                    searchData.add(b);
                }
            }
            return searchData;
        }
        return searchData;
    }

    @Override
    public void OnItemClickListener(View view, int postion) {
        if (AppUtil.isFastClick(300)) {
            return;
        }
        BoxContact boxContact = userList.get(postion);
        boxContact.setUnReadNewsNum(0);
        boxContact.update();
        if(entryMode==1){
            Intent intent=new Intent();
            intent.putExtra("receiverNumber",boxContact.getBoxId());
            intent.putExtra("receiverName",boxContact.getName());
            setResult(RESULT_OK,intent);
            finish();
        }else if(entryMode==2){
            Intent intent=new Intent();
            intent.setClass(this,SendMessageActivity_.class);
            intent.putExtra("receiverNumber",boxContact.getBoxId());
            intent.putExtra("receiverName",boxContact.getName());
            intent.putExtra("entryMode",1);
            startActivity(intent);
        }
    }

    @Override
    public void OnDelClickListener(int postion) {
        Log.e(TAG, "删除:"+postion);
        try {
            BoxContact boxContact = userList.get(postion);
            boxContact.delete();
            SQLite.delete(UserMessageVO.class)
                    .where(UserMessageVO_Table.receiverNumber.eq(boxContact.getBoxId()))
                    .execute();
//            Constant.msgPageIsRefresh=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        updateList();
    }

    final private int refresh_code=6;
    @Override
    public void OnEditClickListener(int postion) {
        Log.e(TAG, "编辑"+postion);
        BoxContact boxContact = userList.get(postion);
//        BoxContact boxContact = userList.get(10);
        Intent intent=new Intent();
        intent.setClass(this, AddContactActivity_.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("boxContact",boxContact);
        intent.putExtras(bundle);
        intent.putExtra("entryMode",1);
        startActivityForResult(intent,refresh_code);
    }

    // 编辑页面返回
    @OnActivityResult(refresh_code)
    public void resultMsgList(int resultCode){
        if(resultCode== Activity.RESULT_OK){
            updateList();
//            Constant.msgPageIsRefresh=true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideInputKeyBord();

    }
}
